package org.simplecrm.repository.user;

import org.simplecrm.domain.user.User;
import org.slf4j.Logger;
import org.springframework.stereotype.Repository;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.LinkedList;
import java.util.List;

/**
 * Implementation for JDBC database.
 */
@Repository("userDAO")
public class UserJdbcDAO implements UserDAO {

    @org.simplecrm.misc.loginject.Logger
    private Logger LOGGER;

    @PersistenceContext(unitName = "entityManager")
    private EntityManager entityManager;

    @Override
    public User getUserByName(String username) {

        User user = new User();

        //TODO: change to NamedQuery from entity EVERYWHERE within DAOs!!!
        Query query = entityManager.createNamedQuery("User.userByName");
        query.setParameter("username", username);
        List<User> userList = query.getResultList();
        if (userList.size() > 1) {
            //TODO: does it a good variant?
            throw new UnsupportedOperationException("There is more then one user with such username!");
        } else {
            user = userList.get(0);
        }

        return user;
    }

    @Override
    public List<User> getUsersByGroupId(Integer groupId) {

        List<User> userList;

        Query query = entityManager.createNamedQuery("User.userByGroup");
        query.setParameter("usergroupId", groupId);
        userList = query.getResultList();
        if (userList == null) {
            userList = new LinkedList<>();
        }

        return userList;
    }
}
